import React,{useCallback} from "react";
import { useNavigate } from "react-router-dom";
import { Button, Input, Form } from "react-vant";
import {Row,Col,message} from 'antd'
import { useSelector, useDispatch } from 'react-redux'
import request from "@/utils/request";

function Login(){
    const navigate = useNavigate()
     // 从redux获取用户数据
     const userInfo = useSelector(function (state) {
        return state.userInfo
    })
    const dispatch = useDispatch()

    const onFinish = (values) => {
        request
            .post("/user/login", { username: values.username, password: values.password })
            .then(({ data }) => {
                if (data.code === 200) {
                    console.log('登录成功', data)
                    dispatch({ type: 'login', payload: data })
                    navigate('/index/mine')
                } else if (data.code === 400) {
                    message.error('用户名或密码错误')
                }
            })
            .catch((err) => {
                console.log(err, "失败");
            });
    };
    
    const goTo = useCallback(function () {
        navigate("/index/mine/reg")
    }, [])
    return (
        <>
            <Row style={{ marginTop: 20, width: 550, height: 220,backgroundColor:'#fff',paddingLeft:126 }}>
                <Form 
                    onFinish={onFinish}
                    footer={
                        <div style={{ margin: "16px 16px 0" }}>
                            <Button round nativeType="submit" type="primary" block>
                                登录
                            </Button>
                        </div>
                    }
                >
                    <Form.Item
                        rules={[{ required: true, message: "请填写用户名" }]}
                        name="username"
                        label="用户名"
                    >
                        <Input placeholder="请输入用户名" />
                    </Form.Item>
                    <Form.Item
                        rules={[{ required: true, message: "请填写密码" }]}
                        name="password"
                        label="密码"
                    >
                        <Input placeholder="请输入密码" type="password" />
                    </Form.Item>
                </Form>
                <Form.Item
                    wrapperCol={{
                        offset: 8,
                        span: 16,
                    }}
                >
                    该不会有人没有账号吧？<Button onClick={goTo}>火速注册</Button>
                </Form.Item>
            </Row>
        </>
    )
}

export default Login;